// 网络配置工具
import { NETWORK_CONFIG } from '@/config/network.js'
const API_BASE_URL = NETWORK_CONFIG.API_BASE_URL;

// 网络请求封装
export const request = async (options) => {
  const { url, method = 'GET', data = {}, header = {} } = options;
  
  // 添加默认请求头
  const defaultHeader = {
    'Content-Type': 'application/json',
    ...header
  };
  
  // 添加token（如果未在header中指定）
  const token = uni.getStorageSync('accessToken');
  if (token && !header['Access-Token'] && !header['access-token']) {
    defaultHeader['Access-Token'] = `Bearer ${token}`;
  }
  
  try {
    const result = await uni.request({
      url: url.startsWith('http') ? url : `${API_BASE_URL}${url}`,
      method,
      data,
      header: defaultHeader,
      timeout: 10000, // 10秒超时
    });
    
    return result;
  } catch (error) {
    console.error('网络请求失败:', error);
    throw new Error('网络连接失败，请检查网络设置');
  }
};

// 检查网络状态
export const checkNetworkStatus = () => {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          uni.showToast({
            title: '网络连接失败，请检查网络设置',
            icon: 'none',
            duration: 3000
          });
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail: () => {
        uni.showToast({
          title: '网络状态检查失败',
          icon: 'none',
          duration: 2000
        });
        resolve(false);
      }
    });
  });
};

// WebSocket连接管理
export class WebSocketManager {
  constructor() {
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 5000; // 5秒
    this.isConnecting = false;
  }
  
  connect(token) {
    if (this.isConnecting) return;
    
    this.isConnecting = true;
    const wsUrl = `wss://${NETWORK_CONFIG.API_BASE_URL}/api/?accessToken=${token}`;
    
    try {
      this.ws = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket连接请求已发送');
        },
        fail: (error) => {
          console.error('WebSocket连接失败:', error);
          this.handleReconnect();
        }
      });
      
      this.ws.onOpen(() => {
        console.log('WebSocket连接已建立');
        this.isConnecting = false;
        this.reconnectAttempts = 0;
      });
      
      this.ws.onError((error) => {
        console.error('WebSocket发生错误:', error);
        this.handleReconnect();
      });
      
      this.ws.onClose(() => {
        console.log('WebSocket连接已关闭');
        this.handleReconnect();
      });
      
      this.ws.onMessage((message) => {
        try {
          const data = JSON.parse(message.data);
          this.handleMessage(data);
        } catch (error) {
          console.error('WebSocket消息解析失败:', error);
        }
      });
      
    } catch (error) {
      console.error('WebSocket连接初始化失败:', error);
      this.handleReconnect();
    }
  }
  
  handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('WebSocket连接失败次数过多，停止重试');
      this.isConnecting = false;
      return;
    }
    
    this.reconnectAttempts++;
    console.log(`将在 ${this.reconnectInterval / 1000} 秒后进行第 ${this.reconnectAttempts} 次重试`);
    
    setTimeout(() => {
      const token = uni.getStorageSync('accessToken');
      if (token) {
        this.connect(token);
      }
    }, this.reconnectInterval);
  }
  
  handleMessage(data) {
    // 处理不同类型的消息
    switch (data.type) {
      case 'task_progress':
        // 触发自定义事件
        uni.$emit('task-progress-update', data);
        break;
      case 'notification':
        uni.showToast({
          title: data.message,
          icon: 'none',
          duration: 3000
        });
        break;
      default:
        console.log('收到WebSocket消息:', data);
    }
  }
  
  send(data) {
    if (this.ws && this.ws.readyState === 1) {
      this.ws.send({
        data: JSON.stringify(data),
        success: () => {
          console.log('WebSocket消息发送成功');
        },
        fail: (error) => {
          console.error('WebSocket消息发送失败:', error);
        }
      });
    } else {
      console.warn('WebSocket未连接，无法发送消息');
    }
  }
  
  close() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    this.isConnecting = false;
    this.reconnectAttempts = 0;
  }
}

// 导出单例
export const wsManager = new WebSocketManager();
